import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Text,
    FlatList,
    TouchableOpacity,
    Image,
} from 'react-native';
import { RRCLoading, RRCToast } from 'react-native-overlayer';
import CheckBox from 'react-native-check-box';
import HttpUtil from '../util/HttpUtil';

let pageNo = 1; //当前第几页
let totalPage = 0; //总的页数

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';

// const data = [
//     { id:1, name:'第三季度盘点', state: 1, owner: '刘云天', total: 299, creatDate:'2019-11-11', finishDate:'', wait: 23, already: 789, surplus: 12, loss: 23 }, 
//     { id:2, name:'第三季度盘点', state: 2, owner: '刘云天', total: 100, creatDate:'2019-11-11', finishDate:'2019-11-12', wait: 23, already: 789, surplus:16, loss: 12 },
//     { id:3, name:'第三季度盘点', state: 1, owner: '刘云天', total: 299, creatDate:'2019-11-11', finishDate:'', wait: 23, already: 789, surplus: 12, loss: 23 }, 
//     { id:4, name:'第三季度盘点', state: 2, owner: '刘云天', total: 100, creatDate:'2019-11-11', finishDate:'2019-11-12', wait: 23, already: 789, surplus:16, loss: 12 },   
//     { id:5, name:'第三季度盘点', state: 1, owner: '刘云天', total: 299, creatDate:'2019-11-11', finishDate:'', wait: 23, already: 789, surplus: 12, loss: 23 }, 
//     { id:6, name:'第三季度盘点', state: 2, owner: '刘云天', total: 100, creatDate:'2019-11-11', finishDate:'2019-11-12', wait: 23, already: 789, surplus:16, loss: 12 },   

// ];

export default class InventoryList extends Component {

    constructor(props){
        super(props);
        this.state = {
            data: [],
            showFoot: 0,
            selectedInventory: [],
        }
    }

    componentDidMount() {
        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })
        RRCLoading.show();
        this.fetchData( pageNo );
    }

    fetchData = ( pageNo ) => {

        let params = {
            pageNum: pageNo,
            pageSize: 10,
        }

        HttpUtil.post('inventoryListData', params)
        .then(result => {         
            if(result.httpCode == 200){
                //console.log(result);
                this.props.setCount(result.data.inventoryCount, result.data.noInventoryCount);
                let foot = 0;
                totalPage = result.data.detailList.pages; //获取总页数
                //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
                if(pageNo>=totalPage){
                    foot = 1;//listView底部显示没有更多数据了
                }
                this.setState({
                    data: [...this.state.data,...result.data.detailList.records],
                    showFoot:foot,
                    
                });
                RRCLoading.hide();
            }else{
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 7000);
            }
        })
        .catch(error => {
            RRCLoading.hide();
            RRCToast.show('系统异常', 1, 7000);
        })
    }

    _onEndReached(){
        //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
             return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((pageNo!=1) && (pageNo>=totalPage)){
            return;
        } else {
            pageNo++;
        }
        //底部显示正在加载更多数据
        this.setState({ showFoot:2 });
        //获取数据
        this.fetchData( pageNo );
    }

    detail=(id)=>{
        this.props.navigation.navigate('InventoryDetail', {
            id: id,
            callBack: () => {
                this.setState({
                    data:[],
                });
                pageNo = 1;
                this.fetchData(pageNo);
            }        
        });
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{ height:getPixel(30), alignItems:'center', marginTop:getPixel(5), justifyContent:'flex-start' }}>
                    <Text style={{ color:'#999999', fontSize:getPixel(14), marginBottom:getPixel(5) }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={{ height:getPixel(30), alignItems:'center', marginTop:getPixel(5), justifyContent:'flex-start' }}>
                    <Text style={{ color:'#999999' }}>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    renderState(id,state){
        if(state == 1){
            return <TouchableOpacity onPress={() => this.detail(id)}><Text style={styles.stateStart}>开始盘点</Text></TouchableOpacity>
        }else if(state == 2){
            return <Text style={styles.stateFinish}>盘点完成</Text>
        }
    }

    renderCheck(id,source){
        if(source == 2){
            return ( 
            <CheckBox
                style={{ flex: 1, width: getPixel(20), height: getPixel(40),  justifyContent: 'flex-start', paddingTop: getPixel(10) }}
                unCheckedImage={ <Image source={ require('../images/unchecked.png')} style={{  resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} /> }
                checkedImage={ <Image source={ require('../images/checked.png')} style={{  resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} /> }
                onClick={ ()=>{
                    let selected = Array.from(this.state.selectedInventory);
                    if(selected.includes(id)){
                        selected.splice(selected.findIndex(i => i === id), 1)
                    }else{
                        selected.push(id);
                    }
                    this.setState({
                        selectedInventory: selected,
                    })
                    this.props.setSelected(selected);
                }}
                isChecked={ this.state.selectedInventory.includes(id) }
                rightTextStyle={{ color: '#999' }}
            />
            )
        }
    }

    renderItem(item){
        return (
            <View key={item.id} style={{ paddingLeft: getPixel(15), paddingRight: getPixel(15), paddingBottom: getPixel(20), paddingTop: getPixel(10), backgroundColor:'#FFF', marginBottom: getPixel(10) }}>
                <View style={styles.title}>
                    <View style={{marginTop: getPixel(2)}}>
                        { this.renderCheck(item.id_,item.source) }
                    </View>
                    <View style={{marginLeft: getPixel(10)}}>
                        <Text style={item.source == 2? [styles.titleText,{ width: getScreenWidth() - getPixel(145), }]: styles.titleText}>{ item.inventorySheetName }</Text>
                    </View>
                    <View style={{ width: getPixel(95), alignItems: 'center' }}>
                        { this.renderState(item.id_,item.status) }
                    </View>
                </View>
                <View style={styles.info}>
                    <View style={styles.infoText}>
                        <Text style={ styles.infoTextTable }>
                            创建人：{item.createName}
                        </Text>
                        <Text style={ [styles.infoTextTable, { marginLeft: getPixel(10) }] }>
                            盘点总数：{item.totalCount}
                        </Text>
                    </View>
                    <View style={styles.infoText}>
                        <Text style={ styles.infoTextTable }>
                            创建日期：{item.createTimeString}
                        </Text>
                        <Text style={ [styles.infoTextTable, { marginLeft: getPixel(10) }] }>
                            完成日期：{item.endTimeString}
                        </Text>
                    </View>
                    <View style={styles.detail}>
                        <View style={styles.detailBox}>
                            <Text style={[styles.detailNum,{ color: '#4A69DD' }]}>{item.noInventoryCount}</Text>
                            <Text style={styles.detailName}>待盘点</Text>
                        </View>
                        <View style={styles.detailBox}>
                            <Text style={styles.detailNum}>{item.inventoryCount}</Text>
                            <Text style={styles.detailName}>已盘点</Text>
                        </View>
                        <View style={styles.detailBox}>
                            <Text style={styles.detailNum}>{item.over}</Text>
                            <Text style={styles.detailName}>盘盈</Text>
                        </View>
                        <View style={[styles.detailBox,{ marginRight: getPixel(0) }]}>
                            <Text style={styles.detailNum}>{item.loss}</Text>
                            <Text style={styles.detailName}>盘亏</Text>
                        </View>
                    </View>
                </View>
            </View> 
        )
    }

    render() {
        return (
            <FlatList
                style={{ backgroundColor: '#F5F5F5',marginTop: getPixel(10) }}
                data={this.state.data}
                renderItem={({item}) => this.renderItem(item)}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={1}
                ListFooterComponent={this._renderFooter.bind(this)}
            >

            </FlatList>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    title: {
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#EEE',
        borderBottomWidth: getPixel(1),
        paddingBottom: getPixel(10),
    },
    titleText: {
        fontSize: getPixel(16),
        color: '#333',
        width: getScreenWidth() - getPixel(125),
    },
    stateStart: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        backgroundColor: '#FFAA2E',
        color: '#FFF',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(8),
        paddingRight: getPixel(8),
    },
    stateFinish: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        backgroundColor: '#4A69DD',
        color: '#FFF',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(8),
        paddingRight: getPixel(8),
    },
    info: {
        justifyContent: 'center',
        marginTop: getPixel(10),
    },
    infoText: {
        flexDirection: 'row',
        alignItems: 'center',
        height: getPixel(30),
    },
    infoTextTable: {
        fontSize: getPixel(14), 
        color:'#999',
        width: getScreenWidth() / 2,
    },
    detail:{
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    detailBox: {
        width: getScreenWidth() / 4 - getPixel(10),
        height: getScreenWidth() / 4 - getPixel(10),
        backgroundColor: '#FAFAFA',
        marginRight: getPixel(1),
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: getPixel(4),
    },  
    detailName: {
        color: '#999',
        paddingTop: getPixel(10),
        fontSize: getPixel(14),
    },
    detailNum: {
        color: '#000',
        fontSize: getPixel(16),
    },
});